import React, { useState, useEffect, useRef } from 'react';
import { Form, DatePicker, Select, Input, Space, Button, Modal, Upload, Pagination, message } from 'antd';
import DraggableTable from '@/components/DraggableTable';
import DataTableActions from './DataTableActions';
import request from '@/utils/request';
import { useNavigate } from 'react-router-dom';
import TopActionBar from '../DataManagement/TopActionBar';
import { restoreColumns, saveColumns, getSortState } from '@/utils/columnStorage';

// ScienceDataPanel 组件
// 用于承载科学数据的筛选、列表、操作等右侧内容
// props 说明见下方注释

// 发布状态映射
const releaseStatusMap = {
  3: '发布中',
  2: '未发布',
  1: '发布成功',
  0: '发布失败'
};
const releaseStatusColor = {
  5: 'gray',
  3: 'blue',
  2: 'orange',
  1: 'green',
  0: 'red'
};

// 复制到剪贴板工具
const copyToClipboard = (text) => {
  const textArea = document.createElement('textarea');
  textArea.value = text;
  textArea.style.position = 'fixed';
  textArea.style.top = '-9999px';
  textArea.style.left = '-9999px';
  document.body.appendChild(textArea);
  textArea.focus();
  textArea.select();
  try {
    const successful = document.execCommand('copy');
    if (successful) {
      message.success('已复制到剪贴板');
    } else {
      message.error('复制失败，请手动复制');
    }
  } catch (err) {
    message.error('复制失败，请手动复制');
  }
  document.body.removeChild(textArea);
};

const ScienceDataPanel = ({
  dataKey,
  visible
}) => {
  const navigate = useNavigate();
  // 所有科学数据相关状态
  const [form] = Form.useForm();
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [dataLevels, setDataLevels] = useState([]);
  const [versionOptions, setVersionOptions] = useState([]);
  const [stationOptions, setStationOptions] = useState([]);
  const [workModeOptions, setWorkModeOptions] = useState([]);
  const [dataLevel, setDataLevel] = useState('');
  const [tableData, setTableData] = useState([]);
  const [tableLoading, setTableLoading] = useState(false);
  const [total, setTotal] = useState(0);
  const [filterParams, setFilterParams] = useState({});
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  // 排序状态
  const [sortState, setSortState] = useState({ field: null, order: null });
  // 定义默认列配置
  const defaultColumns = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      width: 70,
      render: (_, __, idx) => idx + 1 + (current - 1) * pageSize
    },
    {
      title: '文件名',
      dataIndex: 'file_name',
      key: 'file_name',
      width: 300,
      sorter: true,
      ellipsis: { showTitle: false },
      sortDirections: ['ascend', 'descend'],
      render: (text) => (
        <span
          style={{ cursor: 'pointer', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}
          onClick={() => copyToClipboard(text)}
        >
          {text}
        </span>
      )
    },
    {
      title: '存储路径',
      dataIndex: 'file_path',
      key: 'file_path',
      width: 300,
      sorter: true,
      ellipsis: { showTitle: false },
      render: (text) => (
        <span
          style={{ cursor: 'pointer', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}
          onClick={() => copyToClipboard(text)}
        >
          {text}
        </span>
      ),
      sortDirections: ['ascend', 'descend']
    },
    {
      title: '备份状态',
      dataIndex: 'bk_pstate',
      key: 'bk_pstate',
      width: 100,
      render: (value) => (value === 1 ? '已备份' : '未备份'),
      sorter: true,
      sortDirections: ['ascend', 'descend']
    },
    {
      title: '发布状态',
      dataIndex: 'release_status',
      key: 'release_status',
      width: 100,
      sorter: true,
      sortDirections: ['ascend', 'descend'],
      render: (value) => (
        <span style={{ color: releaseStatusColor[value] || 'gray' }}>
          {releaseStatusMap[value] || '未知'}
        </span>
      )
    },
    {
      title: '采集开始时间',
      dataIndex: 'collection_time_start',
      key: 'collection_time_start',
      width: 180,
      sorter: true,
      sortDirections: ['ascend', 'descend']
    },
    {
      title: '采集结束时间',
      dataIndex: 'collection_time_end',
      key: 'collection_time_end',
      width: 180,
      sorter: true,
      sortDirections: ['ascend', 'descend']
    },
    {
      title: '归档时间',
      dataIndex: 'archive_time',
      key: 'archive_time',
      width: 180,
      sorter: true,
      sortDirections: ['ascend', 'descend']
    },
    {
      title: '数据大小(MB)',
      dataIndex: 'data_size',
      key: 'data_size',
      width: 140,
      sorter: true,
      sortDirections: ['ascend', 'descend'],
      render: (value) => (value / 1024 / 1024).toFixed(2)
    },
    {
      title: '任务型号',
      dataIndex: 'task_type',
      key: 'task_type',
      width: 100,
      sorter: true,
      sortDirections: ['ascend', 'descend']
    },
    {
      title: '接收站',
      dataIndex: 'station',
      key: 'station',
      width: 100,
      sorter: true,
      sortDirections: ['ascend', 'descend']
    },
    {
      title: '载荷',
      dataIndex: 'dm_zhname',
      key: 'dm_zhname',
      width: 100,
      sorter: true,
      sortDirections: ['ascend', 'descend']
    },
    {
      title: '版本号',
      dataIndex: 'version_num',
      key: 'version_num',
      width: 100,
      sorter: true,
      sortDirections: ['ascend', 'descend']
    },
    {
      title: '轨道圈数/探测周期编号',
      dataIndex: 'track_num_turns',
      key: 'track_num_turns',
      width: 190,
      sorter: true,
      sortDirections: ['ascend', 'descend']
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      fixed: 'right',
      align: 'center' as const,
      render: (_ , record) => renderActionColumn(_, record)
    }
  ];
  
  // 初始化列配置，从localStorage恢复
  const [columns, setColumns] = useState(() => {
    const tableKey = 'data_search_science_table';
    return restoreColumns(defaultColumns, tableKey);
  });
  
  const [archiveModalVisible, setArchiveModalVisible] = useState(false);
  const [uploadFileList, setUploadFileList] = useState([]);
  const tableContainerRef = useRef(null);
  const [tableScrollY, setTableScrollY] = useState(0);
  // TopActionBar ref
  const topActionBarRef = useRef(null);
  // 新增visibleRef，保证事件回调拿到最新visible
  const visibleRef = useRef(visible);
  useEffect(() => {
    visibleRef.current = visible;
  }, [visible]);

  // 监听操作列变化
  useEffect(() => {
    setColumns((prevColumns) => {
      if (!prevColumns) return prevColumns;
      return prevColumns.map((col) => {
        if (col.key === 'action') {
          return {
            ...col,
            render: renderActionColumn
          };
        }
        return col;
      });
    });
  }, [current, pageSize, dataLevel, sortState, filterParams]);

  // 保存列配置到localStorage
  useEffect(() => {
    if (columns.length > 0) {
      const tableKey = 'data_search_science_table';
      saveColumns(columns, tableKey, sortState);
    }
  }, [columns, sortState]);

  // 获取数据等级信息
  const fetchDataLevel = async () => {
    try {
      if (!dataKey) return;
      const response = await request.get('/Management/DataLevel', {
        params: { data_key: dataKey, ...filterParams }
      });
      if (response.status === 200) {
        const { data_level } = response.data.data;
        const newDataLevels = data_level.map((item) => ({
          key: item.level,
          label: item.level === '' ? '全部' : `${item.level}级`,
          count: item.count,
          size: `${(item.size / 1024 / 1024 / 1024).toFixed(2)}GB`
        }));
        setDataLevels(newDataLevels);
      }
    } catch (error) {
      message.error(error?.message || '获取数据等级信息失败');
    }
  };

  // 获取筛选选项
  const fetchFilterOptions = async () => {
    try {
      if (!dataKey) return;
      const response = await request.get('/Management/DataFilterOptions', {
        params: { data_key: dataKey, data_level: dataLevel }
      });
      if (response.status === 200) {
        const { work_modes, version_nums, station } = response.data.data;
        setWorkModeOptions(work_modes || []);
        setVersionOptions(version_nums || []);
        setStationOptions(station || []);
      }
    } catch (error) {
      message.error(error?.message || '获取筛选选项失败');
    }
  };

  // 获取数据列表
  const abortControllerRef = useRef(null);
  const fetchTableData = async () => {
    if (abortControllerRef.current) {
      abortControllerRef.current.abort();
    }
    abortControllerRef.current = new AbortController();
    const signal = abortControllerRef.current.signal;
    setTableLoading(true);
    try {
      if (filterParams.track_num_turns__gte && filterParams.track_num_turns__lte) {
        if (Number(filterParams.track_num_turns__lte) < Number(filterParams.track_num_turns__gte)) {
          message.error('结束轨道圈数不能小于起始轨道圈数');
          return;
        }
      }
      if (!dataKey) return;
      const queryParams = {
        data_key: dataKey,
        ...filterParams,
        data_level: dataLevel,
        ordering: sortState.field ? `${sortState.order === 'descend' ? '-' : ''}${sortState.field}` : undefined,
        page: current,
        page_size: pageSize
      };
      const response = await request.get('/Management/DataList', {
        params: queryParams,
        signal
      });
      if (response.status === 200) {
        const { list, count, page } = response.data.data;
        const formattedData = list.map((item) => ({
          key: item.product_id,
          file_name: item.file_name,
          file_path: item.file_path,
          bk_pstate: item.bk_pstate,
          data_type: item.data_type,
          release_status: item.release_status,
          collection_time_start: item.collection_time_start,
          collection_time_end: item.collection_time_end,
          archive_time: item.archive_time,
          data_size: item.data_size,
          task_type: item.task_type,
          station: item.station,
          dm_zhname: item.dm_zhname,
          version_num: item.version_num,
          track_num_turns: item.track_num_turns,
          is_favorites: item.is_favorites
        }));
        setTableData(formattedData);
        setCurrent(page);
        setTotal(count);
      }
    } catch (error) {
      if (error.name === 'CanceledError' || error.name === 'AbortError') {
        return;
      }
      message.error(error?.message || '获取数据列表失败');
    } finally {
      setTableLoading(false);
    }
  };

  // 监听dataKey变化，重新获取数据等级和筛选选项
  useEffect(() => {
    if (dataKey) {
      // 重新加载列配置和排序状态
      const tableKey = 'data_search_science_table';
      setColumns(restoreColumns(defaultColumns, tableKey));
      const savedSortState = getSortState(tableKey);
      setSortState(savedSortState || { field: null, order: null });
      
      fetchDataLevel();
      fetchFilterOptions();
      setFilterParams({});
      form.resetFields();
      setCurrent(1);
      setDataLevel('');
    }
  }, [dataKey]);

  // 监听数据等级变化，重新获取筛选选项
  useEffect(() => {
    if (dataKey) {
      fetchFilterOptions();
      setCurrent(1);
    }
  }, [dataLevel]);

  // 监听分页和筛选条件变化，重新获取表格数据
  useEffect(() => {
    if (dataKey) {
      fetchTableData();
    }
  }, [current, pageSize, dataLevel, sortState, filterParams]);

  useEffect(() => {
    if (dataKey) {
      fetchDataLevel();
    }
  }, [filterParams]);

  // 筛选表单提交
  const onFinish = (values) => {
    if (values.collection_time_range) {
      values.collection_time__gte = values.collection_time_range[0]?.format('YYYY-MM-DD 00:00:00');
      values.collection_time__lte = values.collection_time_range[1]?.format('YYYY-MM-DD 23:59:59');
      delete values.collection_time_range;
    }
    if (values.archive_time_range) {
      values.archive_time__gte = values.archive_time_range[0]?.format('YYYY-MM-DD 00:00:00');
      values.archive_time__lte = values.archive_time_range[1]?.format('YYYY-MM-DD 23:59:59');
      delete values.archive_time_range;
    }
    setCurrent(1);
    setFilterParams(values);
  };

  // 收藏、删除、取消发布等操作
  const handleFavorite = async (record) => {
    try {
      const payload = {
        files: [
          {
            data_type: record.data_type,
            product_id: record.key
          }
        ]
      };
      const response = await request.post('/Management/Favorites', payload);
      if (response.status === 200) {
        message.success('收藏成功');
        setTableData((prevData) => prevData.map((item) => (item.key === record.key ? { ...item, is_favorites: 1 } : item)));
      }
    } catch (error) {
      message.error(error?.message || '收藏失败');
    }
  };

  // 取消收藏
  const handleUnfavorite = async (record) => {
    try {
      const response = await request.post('/Management/FavoritesCancel', {
        file_ids: [record.key]
      });
      if (response.status === 200) {
        message.success('取消收藏成功');
        setTableData((prevData) => prevData.map((item) => (item.key === record.key ? { ...item, is_favorites: 0 } : item)));
      }
    } catch (error) {
      message.error(error?.message || '取消收藏失败');
    }
  };

  // 新增：单个文件下载功能
  const handleDownload = (record) => {
    if (!record.key) {
      message.warning('缺少product_id，无法下载');
      return;
    }
    const url = request.getUrl(`/Management/Download?data_type=${record.data_type}&product_id=${record.key}`);
    window.open(url, '_blank');
  };

  const handleDelete = async (record) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除文件"${record.file_name}"吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          const payload = {
            files: [
              {
                data_type: record.data_type,
                product_id: record.key
              }
            ]
          };
          const response = await request.post('/Management/DataDelete', payload);
          if (response.status === 200) {
            message.success('删除成功');
            await fetchTableData();
            await fetchDataLevel();
            await fetchFilterOptions();
          }
        } catch (error) {
          message.error(error?.message || '删除失败');
        }
      }
    });
  };
  const handleCancelRelease = async (record) => {
    Modal.confirm({
      title: '确认取消发布',
      content: `确定要取消发布文件"${record.file_name}"吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          const payload = {
            files: [
              {
                data_type: record.data_type,
                product_id: record.key
              }
            ]
          };
          const response = await request.post('/Management/DataCancelRelease', payload);
          if (response.status === 200) {
            message.success('取消发布成功');
            await fetchTableData();
          }
        } catch (error) {
          message.error(error?.message || '取消发布失败');
        }
      }
    });
  };

  // 操作列渲染
  const renderActionColumn = (_, record) => (
    <Space>
      <Button size="small" icon={<span>↓</span>} onClick={() => handleDownload(record)}>
        下载
      </Button>
      {record.is_favorites ? (
        <Button 
          size="small" 
          icon={<span style={{ color: '#ffd700' }}>★</span>} 
          onClick={() => handleUnfavorite(record)}
        >
          收藏
        </Button>
      ) : (
        <Button size="small" icon={<span>★</span>} onClick={() => handleFavorite(record)}>
          收藏
        </Button>
      )}
    </Space>
  );

  // 表格滚动高度自适应
  const calculateTableScrollHeight = () => {
    if (visibleRef.current && tableContainerRef.current) {
      const containerHeight = tableContainerRef.current.clientHeight;
      const tableHeaderHeight = 42;
      const scrollHeight = containerHeight - tableHeaderHeight;
      setTableScrollY(scrollHeight);
      const body = tableContainerRef.current.querySelector('.ant-table-body');
      if (body) {
        body.style.height = Math.max(scrollHeight, 0) + 'px';
      }
    }
  };
  
  useEffect(() => {
    window.addEventListener('resize', calculateTableScrollHeight);
    return () => {
      window.removeEventListener('resize', calculateTableScrollHeight);
    };
  }, []);

  useEffect(() => {
    calculateTableScrollHeight();
  }, [visible, dataLevels]);

  // 行选择配置
  const rowSelection = {
    selectedRowKeys,
    columnWidth: 50,
    onChange: (keys) => setSelectedRowKeys(keys)
  };

  // 清除筛选条件并重置分页
  const handleClear = () => {
    form.resetFields();
    form.setFieldsValue({});
    setCurrent(1);
    setFilterParams({});
  };

  return (
    <div
      className="data-management-right"
      style={{ flex: '1', overflow: 'auto', minWidth: 0, width: '100%', display: visible ? 'flex' : 'none' }}
    >
      {/* 顶部筛选区 */}
      <Form form={form} layout="inline" className="filter-form" onFinish={onFinish} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}>
        {/* 采集时间范围选择器 */}
        <Form.Item label="采集时间" style={{ width: 320 }} name="collection_time_range">
          <DatePicker.RangePicker style={{ width: '100%' }} placeholder={['开始时间', '结束时间']} />
        </Form.Item>
        {/* 归档时间范围选择器 */}
        <Form.Item label="归档时间" style={{ width: 320 }} name="archive_time_range">
          <DatePicker.RangePicker style={{ width: '100%' }} placeholder={['开始时间', '结束时间']} />
        </Form.Item>
        {/* 版本号独立筛选 */}
        <Form.Item name="version_num" label="版本号" style={{ width: 320 }}>
          <Select allowClear placeholder="请选择版本号" style={{ width: '100%' }}>
            {versionOptions.map((option) => (
              <Select.Option key={option} value={option}>
                {option}
              </Select.Option>
            ))}
          </Select>
        </Form.Item>
        {/* 轨道圈数区间筛选 */}
        <Form.Item 
          label="轨道圈数/探测周期编号" 
          style={{ 
            width: 320,
            '--ant-form-item-label-width': '160px'
          } as React.CSSProperties}
        >
          <Space style={{ width: '100%' }}>
            <Form.Item name="track_num_turns__gte" noStyle style={{ flex: 1 }}>
              <Input type="number" placeholder="起始" style={{ width: '70px' }} min={0} />
            </Form.Item>
            <span style={{ color: '#999' }}>—</span>
            <Form.Item name="track_num_turns__lte" noStyle style={{ flex: 1 }}>
              <Input type="number" placeholder="结束" style={{ width: '70px' }} min={0} />
            </Form.Item>
          </Space>
        </Form.Item>
        <Form.Item name="work_mode" label="工作模式" style={{ width: 320 }}>
          <Select allowClear placeholder="请选择工作模式" style={{ width: '100%' }}>
            {workModeOptions.map((option) => (
              <Select.Option key={option} value={option}>
                {option}
              </Select.Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item name="station" label="接收站" style={{ width: 320 }}>
          <Select allowClear placeholder="请选择接收站" style={{ width: '100%' }}>
            {stationOptions.map((option) => (
              <Select.Option key={option} value={option}>
                {option}
              </Select.Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item style={{ paddingLeft: 80, width: 320 }}>
          <Space>
            <Button type="primary" htmlType="submit">
              筛选
            </Button>
            <Button htmlType="button" onClick={handleClear}>
              清除
            </Button>
          </Space>
        </Form.Item>
      </Form>
      {/* 固定项筛选条 */}
      <div className="fixed-filter-tabs">
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', width: '100%' }}>
          <div
            style={{
              overflowX: 'auto',
              whiteSpace: 'nowrap',
              overflowY: 'hidden',
              marginRight: 10,
              lineHeight: '22px'
            }}
          >
            {dataLevels.map((tab, i) => (
              <span
                key={tab.key}
                className={`filter-tab-item${dataLevel === tab.key ? ' active' : ''}`}
                style={{ marginRight: i === dataLevels.length - 1 ? 0 : 16 }}
                onClick={() => setDataLevel(tab.key)}
              >
                {tab.label}({tab.count}/{tab.size})
              </span>
            ))}
          </div>
          <div>
            <TopActionBar ref={topActionBarRef} showReleaseHistory={false} />
          </div>
        </div>
      </div>
      {/* 数据表格 */}
      <div ref={tableContainerRef} style={{ flex: 1, overflow: 'hidden' }}>
        <DraggableTable
          rowSelection={rowSelection}
          columns={columns}
          dataSource={tableData}
          pagination={false}
          tableLayout="fixed"
          style={{ flex: 1 }}
          scroll={{
            y: tableScrollY,
            x: 'max-content'
          }}
          bordered
          size="small"
          loading={tableLoading}
          rowClassName={(_, index) => (index % 2 === 0 ? 'zebra-row-odd' : 'zebra-row-even')}
          onChange={(pagination, filters, sorter) => {
            if (sorter.field) {
              setSortState({
                field: sorter.field,
                order: sorter.order
              });
            }
          }}
          onColumnsChange={(columns) => {
            setColumns(columns);
          }}
        />
      </div>
      {/* 表格下方操作按钮和分页 */}
      <div
        className="table-footer-bar"
        style={{ marginTop: 0, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <div className="action-buttons" style={{ marginBottom: 0, boxShadow: 'none', borderRadius: 0, background: 'none', padding: 0 }}>
          <DataTableActions
            selectedRowKeys={selectedRowKeys}
            setSelectedRowKeys={setSelectedRowKeys}
            dataKey={dataKey}
            tableData={tableData}
            filterParams={filterParams}
            dataLevel={dataLevel}
            fetchTableData={fetchTableData}
            fetchDataLevel={fetchDataLevel}
            fetchFilterOptions={fetchFilterOptions}
            refreshDownloadingCount={() => {
              try { (topActionBarRef.current as any)?.refreshDownloadingCount?.(); } catch(e) {}
            }}
          />
        </div>
        <Pagination
          current={current}
          pageSize={pageSize}
          total={total}
          showSizeChanger
          style={{ marginTop: 0 }}
          pageSizeOptions={['10', '20', '50']}
          onChange={(page, size) => {
            setCurrent(page);
            setPageSize(size);
          }}
          showTotal={(total) => `共 ${total} 条`}
        />
      </div>
      {/* 手动归档弹窗 */}
      <Modal
        title="手动归档"
        open={archiveModalVisible}
        onCancel={() => setArchiveModalVisible(false)}
        footer={[
          <Button key="cancel" onClick={() => setArchiveModalVisible(false)}>
            取消
          </Button>,
          <Button
            key="submit"
            type="primary"
            onClick={() => {
              setArchiveModalVisible(false);
              message.success('提交成功（仅演示）');
            }}>
            提交
          </Button>
        ]}>
        <Upload.Dragger
          multiple
          accept=".xlsx"
          fileList={uploadFileList}
          onChange={({ fileList }) => setUploadFileList(fileList)}
          beforeUpload={() => false}>
          <p className="ant-upload-drag-icon">
            {/* 这里可以放上传图标 */}
          </p>
          <p className="ant-upload-text">点击或拖拽文件到此区域上传</p>
          <p className="ant-upload-hint">支持扩展名：.xlsx</p>
        </Upload.Dragger>
      </Modal>
    </div>
  );
};

export default ScienceDataPanel; 